package com.mf.utils;

import com.mf.entity.RecommendCode;
import com.mf.vo.MACD.MACDVo;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: MACD
 * Package: com.mf.config
 * Description:
 *
 * @Author: lmf
 * @Create: 2024/4/30 16:07
 * @Version: 1.0
 */
public class MACDUtils {
    // 计算MACD的方法
    public static MACDVo calculateMacd(List<RecommendCode> stockDataList,
                                                 int shortPeriod, int longPeriod, int signalPeriod) {

        System.out.println(stockDataList.get(0).getDm()+"代码");
        if (stockDataList == null || stockDataList.isEmpty() ||
                shortPeriod <= 0 || longPeriod <= 0 || signalPeriod <= 0 || shortPeriod >= longPeriod) {
            throw new IllegalArgumentException("Invalid input parameters");
        }

        int n = stockDataList.size();
        double[] shortEma = new double[n];
        double[] longEma = new double[n];
        double[] signalLine = new double[n];
        double[] macdLine = new double[n];
        double[] dif = new double[n];
        String[] date = new String[n];

        final double c = stockDataList.get(0).getC();
        // 计算短期（指数移动平均）
        shortEma[0] = c;
        // 计算长期的EMA（指数移动平均）
        longEma[0] = c;

        // 计算DEA (差离平均值)
        signalLine[0] = dif[0];
        for (int i = 1; i < n; i++) {
            double k = 2.0 / (shortPeriod + 1);
            final double p1 = stockDataList.get(i).getC();
            // 计算短期EMA
            shortEma[i] = (p1 - shortEma[i - 1]) * k + shortEma[i - 1];

            double k2 = 2.0 / (longPeriod + 1);
            // 计算长期的EMA
            longEma[i] = (p1 - longEma[i - 1]) * k2 + longEma[i - 1];

            //  计算DIF (差离值)
            dif[i] = shortEma[i] - longEma[i];

            // 计算DEA (差离平均值)
            double k3 = 2.0 / (signalPeriod + 1);
            signalLine[i] = (dif[i] - signalLine[i - 1]) * k3 + signalLine[i - 1];

            // 计算MACD线 (DIF - DEA)    * 2 --> 为了更好的展示
            macdLine[i] = (dif[i] - signalLine[i]) * 2;

            date[i] = stockDataList.get(i).getD();
        }
        // 创建结果列表
        MACDVo result = new MACDVo();
        result.setMacd(macdLine);
        result.setDif(dif);
        result.setDea(signalLine);
        result.setDate(date);
        return result;
    }
}
